'use strict';

var Match = {
    players: ['A', 'B'],
    history: [],
    current_game: document.querySelectorAll('#game button'),
    sets: [document.querySelectorAll('#playerA .set'),
    document.querySelectorAll('#playerB .set')],
    type: document.querySelector('select[name="type"]'),
    scores: ['0', '15', '30', '40'],
    init: function init() {
        for (var button of document.querySelectorAll('button')) {
            button.addEventListener('mousedown', this);
            button.addEventListener('touchstart', function(evt) {
                evt.target.classList.add('active');
            });
            button.addEventListener('touchend', function(evt) {
                evt.target.classList.remove('active');
            });
        }
        this.type.addEventListener('change', this);
        this.display();
    },
    handleEvent: function handleEvent(evt) {
        var target = evt.target;
        if (evt.type == 'mousedown') {
            if (target.dataset.player && !this.end) {
                this.point(this.players.indexOf(target.dataset.player));
            }
            if (target.id == 'reset') {
                this.reset();
            }
            if (target.id == 'undo') {
                this.undo();
            }
        }
        this.display();
    },
    point: function point(player) {
        this.history.push(player);
    },
    reset: function reset() {
        this.history = [];
    },
    undo:function undo() {
        this.history.pop();
    },
    display: function display() {
        var points = [0, 0];
        var games = [[0, 0]];

        var add_point = function add_point(player) {
            points[player] += 1;
            points.forEach(win_game);
        }

        var win_game = function win_game(point, player, array) {
            var other = array[(player + 1) % 2];
            var tb = tie_break();
            if ((!tb && ((point > 3) && ((other < 3) ||
                                (point > other + 1)))) ||
                    (tb && ((point > 5) && (point > other + 1)))) {
                points = [0, 0];
                add_game(player);
            }
        };

        var add_game = function add_game(player) {
            var last = games[games.length - 1];
            last[player] += 1;
            var game = last[player];
            var other = last[(player + 1) % 2];
            if (((game == 6) && (other < 5)) || (game > 6)) {
                games.push([0, 0]);
            }
        };

        var tie_break = function tie_break() {
            var game = games[games.length - 1];
           return (game[0] == 6) && (game[1] == 6);
        };

        this.history.forEach(add_point);

        var sets = [0, 0];
        var type = parseInt(this.type.value);
        for (var i = 0; i < games.length; i++) {
            var current = games[i];
            current.forEach(function(game, player) {
                var other = current[(player + 1) % 2];
                if (((game == 6) && (other < 5)) || (game > 6)) {
                    sets[player] += 1;
                }
            });
        }
        this.end = sets.reduce(function(previous, current) {
            return previous || (current >= type);
        }, false);

        points.forEach(function set_point(point, i) {
            var content = this.scores[point];
            if (tie_break()) {
                content = point;
            } else if (point > 3) {
                var other = points[(i + 1) % 2];
                if (point > other) {
                    content = 'A';
                } else {
                    content = '40';
                }
            }
            this.current_game[i].textContent = content;
        }.bind(this));
        for (var i = 0; i < 5; i++) {
            var game = games[i];
            var empty = '0';
            if (i >= 2 * type -1) {
                empty = '';
            }
            this.sets[0][i].textContent = game ? game[0] : empty;
            this.sets[1][i].textContent = game ? game[1] : empty;
        }
    }
};

window.addEventListener('load', function load(evt) {
    window.removeEventListener('load', load);
    Match.init();
});
